package com.contactbook.web.controller.account;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.contactbook.web.service.AccountClient;
import com.contactbook.web.util.AccountMessage;

import contactbook.model.Account;

public class AddAccountController extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;
	
	private static final String CONFIRM_ADD = "Ajouter";
	
	private AccountClient accountClient;
	
	public AddAccountController() {
		super();
    	accountClient = new AccountClient();
	}
	
   public void init() throws ServletException {
    	super.init();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		Account account = (Account)session.getAttribute("account");
		String submit = request.getParameter("submit");
		RequestDispatcher dispatcher = request.getRequestDispatcher("/Index");
		
		if (submit == null) {
			dispatcher = request.getRequestDispatcher("/addAccount.jsp");
		}
		else if (account == null && submit.equals(CONFIRM_ADD)) {
			AccountMessage message = addAccount(request);
			request.setAttribute("login", request.getParameter("login"));
			request.setAttribute("message", message);
			
			dispatcher = request.getRequestDispatcher("/addAccount.jsp");
		}
		
		dispatcher.forward(request, response);
	}

	private AccountMessage addAccount(HttpServletRequest request) {
		Account account;
		HttpSession session = request.getSession(true);
		
		String login = request.getParameter("login");
		String password = request.getParameter("password");
		String confirmPassword = request.getParameter("confirm_password");
		
		if (!login.equals("") && !password.equals("")) {
			if (password.equals(confirmPassword)) {
				account = accountClient.create(new Account(login, password));
				if (account != null)
					account = accountClient.login(login, password);
				if (account != null) {
		        	session.setAttribute("account", account);
		        	return AccountMessage.ACCOUNT_CREATED_OK;
				}
				else
					return AccountMessage.ACCOUNT_CREATED_ALREADY_EXISTS;
			}
			else
				return AccountMessage.ACCOUNT_CREATED_PWD_CONFIRM_FAIL;
		}
		return AccountMessage.ACCOUNT_CREATED_FORM_FAIL;
	}
	
	public void destroy() {
		super.destroy();
	}		

}
